package com.yeskery.nut.extend.mybatis;

import com.yeskery.nut.transaction.TransactionManager;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.managed.ManagedTransaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;

/**
 * nut事务对象
 * @author Yeskery
 * 2023/7/25
 */
public class NutTransaction extends ManagedTransaction {

    /** 事务管理器对象 */
    private final TransactionManager transactionManager;

    /**
     * 构建nut事务对象
     * @param transactionManager 事务管理器
     * @param connection 连接对象
     * @param closeConnection 是否关闭连接
     */
    public NutTransaction(TransactionManager transactionManager, Connection connection, boolean closeConnection) {
        super(connection, closeConnection);
        this.transactionManager = transactionManager;
    }

    /**
     * 构建nut事务对象
     * @param transactionManager 事务管理器
     * @param ds 数据源
     * @param level 事务隔离级别
     * @param closeConnection 是否关闭连接
     */
    public NutTransaction(TransactionManager transactionManager, DataSource ds, TransactionIsolationLevel level, boolean closeConnection) {
        super(ds, level, closeConnection);
        this.transactionManager = transactionManager;
    }

    @Override
    public Connection getConnection() throws SQLException {
        Optional<Connection> optional = transactionManager.getCurrentConnectionOptional();
        if (optional.isPresent()) {
            return optional.get();
        }
        return super.getConnection();
    }

    @Override
    public void commit() throws SQLException {
        transactionManager.commitTransaction();
    }

    @Override
    public void rollback() throws SQLException {
        transactionManager.rollbackTransaction();
    }
}
